package com.accgm.api.resources.user;

import java.util.Date;
import java.util.HashMap;

import net.sf.json.JSONObject;

import org.restlet.Request;

import com.accgm.api.db.dao.AccgmUserDao;
import com.accgm.api.db.model.AccgmUserModel;
import com.accgm.api.resources.base.BaseResource;
import com.accgm.api.utils.Encryptstr;

public class UserRegisterResource extends BaseResource {
	
	AccgmUserDao accgmUserDao = AccgmUserDao.getInstance();
	@Override
	protected void initParams(Request request) {
		isAuth = false;
	}

	@Override
	protected JSONObject getMethod(JSONObject json) {
		String username = getParameter("username","");//姓名
		String sex = getParameter("sex","");//性别
		String birthday = getParameter("birthday","");//出生日期
		String height = getParameter("height","");//身高
		String weight = getParameter("weight","");//体重
		Integer medical = getParameter("medical",0);//糖尿病类型
		String ear_lobe = getParameter("ear_lobe","");//耳垂厚度
		String ear_hole = getParameter("ear_hole","");//是否穿耳环
		String password = getParameter("password","");//密码
		
		if(password == ""){
			password = "000";
		}
		
		AccgmUserModel accgmUser = new AccgmUserModel();
		accgmUser.setName(username);
		accgmUser.setSex(sex);
		accgmUser.setAddTime(new Date());
		accgmUser.setBirthday(birthday);
		accgmUser.setCheckMessage(medical);
		accgmUser.setEarlobeWidth(ear_lobe);
		accgmUser.setHeight(height);
		accgmUser.setIsEarPiercing(ear_hole);
		try {
			String key = "A1B2C3D4E5F60708";
			accgmUser.setPassword(Encryptstr.encrypt(password));
		} catch (Exception e) {
			e.printStackTrace();
		}
		accgmUser.setUpdateTime(new Date());
		accgmUser.setWeight(weight);
		int id = accgmUserDao.insert(accgmUser);
		AccgmUserModel updateAccgmUser = new AccgmUserModel();
		updateAccgmUser.setId(id);
		updateAccgmUser.setUsername("A"+this.getUsername(id));
		accgmUserDao.updateAny(updateAccgmUser);
		HashMap<String,String> data = new HashMap<String,String>();
		data.put("account", updateAccgmUser.getUsername());
		json.put("data", data);
		return succRequest("注册成功",json);
	}

	@Override
	protected JSONObject postMethod(JSONObject json) {
		return this.getMethod(json);
	}
	
	public String getUsername(Integer id){
		String usernameNumber = (id - 100000000)+"";
		while(true){
			if(usernameNumber.length() < 4){
				usernameNumber = "0"+usernameNumber;
			}
			else{
				break;
			}
		}
		return usernameNumber;
	}

//	public static void main(String args[]){
//		System.out.println(new UserRegisterResource());
//	}

}
